package com.lwl.concurrency.forkjoin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author liwenlong - 2018/3/30 15:53
 */
public class CountTask2 extends RecursiveTask<Long> {

    private static final int threshold = 10000;
    private long start;
    private long end;
    private AtomicInteger atomicInteger;

    public CountTask2(long start, long end, AtomicInteger atomicInteger) {
        this.start = start;
        this.end = end;
        this.atomicInteger = atomicInteger;
    }

    @Override
    protected Long compute() {
        atomicInteger.getAndAdd(1);
        long sum = 0;
        boolean canCompute = (end - start) < threshold;
        if (canCompute) {
            System.out.println(Thread.currentThread().getName());
            for (long i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            //分成100个小任务
            long step = (start + end) / 100;
            ArrayList<CountTask2> subTasks = new ArrayList<>();
            long pos = start;
            for (int i = 0; i < 100; i++) {
                long lastOne = pos + step;
                if (lastOne > end) {
                    lastOne = end;
                }
                CountTask2 subTask = new CountTask2(pos, lastOne, atomicInteger);
                subTasks.add(subTask);
                pos += step + 1;
                subTask.fork();
            }
            for (CountTask2 subTask : subTasks) {
                sum += subTask.join();
            }
        }
        System.out.println(atomicInteger.get());
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /*ForkJoinPool forkJoinPool = new ForkJoinPool();

        AtomicInteger atomicInteger = new AtomicInteger();
        CountTask2 task = new CountTask2(0, 200000L, atomicInteger);
        ForkJoinTask<Long> result = forkJoinPool.submit(task);
        System.out.println("结果 "+result.get());*/

        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
        Arrays.stream(arr).map((x) -> x = x + 1).forEach(System.out::println);


    }
}
